package com.example.sociamedia.user.controller;


import com.example.sociamedia.user.dto.*;
import com.example.sociamedia.user.mapper.UserMapper;
import com.example.sociamedia.user.entity.User;
import com.example.sociamedia.user.until.PasswordUtil;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UserService implements UserApi {


    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    @Transactional
    public UserResponse registerUser(UserRequest userRequest) {
        // 检查用户名是否已存在
        if (userMapper.selectUserByName(userRequest.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        // 检查邮箱是否已存在
        if (userMapper.selectUserByEmail(userRequest.getEmail()) != null) {
            throw new RuntimeException("该邮箱已被注册");
        }
        // 创建用户实体，后边用于插入数据库中
        User user = new User();
        user.setUsername(userRequest.getUsername());
        user.setEmail(userRequest.getEmail());
        user.setFullname(userRequest.getFullname());
        user.setBio(userRequest.getBio());
        user.setProfilepictureurl(userRequest.getProfilepictureurl() != null ? userRequest.getProfilepictureurl() : "default.jpg");
        // 加密密码
        String hashedPassword = PasswordUtil.hashPassword(userRequest.getPassword());
        user.setPasswordhash(hashedPassword);
        // 插入用户
        userMapper.insertUser(user);
        // 返回响应DTO
        return convertToResponse(user);
    }

    @Override
    public UserResponse getUserProfile(Long userid) {
        User user = userMapper.selectUserById(userid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToResponse(user);
    }

    @Override
    @Transactional
    public void updateUserProfile(Long userid, UserRequest userRequest) {
        User user = userMapper.selectUserById(userid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        user.setUsername(userRequest.getUsername());
        user.setEmail(userRequest.getEmail());
        user.setFullname(userRequest.getFullname());
        user.setBio(userRequest.getBio());
        user.setProfilepictureurl(userRequest.getProfilepictureurl());

        userMapper.updateUserProfile(user);
    }

    @Override
    @Transactional
    public void changePassword(Long userid, String oldPassword, String newPassword) {
        User user = userMapper.selectUserById(userid);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码
        if (!PasswordUtil.verifyPassword(oldPassword, user.getPasswordhash())) {
            throw new RuntimeException("旧密码不正确");
        }

        // 更新密码
        String hashedNewPassword = PasswordUtil.hashPassword(newPassword);
        userMapper.updatePassword(userid, hashedNewPassword);
    }

    @Override
    @Transactional
    public  LoginResponse userLogin(LoginRequest loginrequest){


        User user = userMapper.selectUserByName(loginrequest.getUsername());

        if (user == null) {
            throw new RuntimeException("用户名错误");
        }
        else if (!PasswordUtil.verifyPassword(loginrequest.getPassword(), user.getPasswordhash())) {
            throw new RuntimeException("密码错误");
        }
        else {

            String token = UUID.randomUUID().toString();//生成token
            LocalDateTime expiryTime = LocalDateTime.now().plusHours(2);  // 2小时后

            user.setSessionToken(token);
            user.setTokenExpiry(expiryTime);
            userMapper.updateSessionToken(user);

            return convertLoginResponse(user);
        }

    }

    @Transactional
    public void logout(LogoutRequest logoutRequest) {
        User user = userMapper.selectUserByName(logoutRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setSessionToken(null);
        user.setTokenExpiry(null);
        userMapper.updateSessionToken(user);
    }

    private UserResponse convertToResponse(User user) {
        UserResponse response = new UserResponse();
        response.setUserid(user.getUserid());
        response.setUsername(user.getUsername());
        response.setEmail(user.getEmail());
        response.setFullname(user.getFullname());
        response.setBio(user.getBio());
        response.setProfilepictureurl(user.getProfilepictureurl());
        response.setCreatedat(user.getCreatedat());
        return response;
    }

    private LoginResponse convertLoginResponse(User user) {
        LoginResponse loginresponse = new LoginResponse();
        loginresponse.setUsername(user.getUsername());
        loginresponse.setSessionToken(user.getSessionToken());
        loginresponse.setTokenExpiry(user.getTokenExpiry());
        loginresponse.setMessage("登录成功");
        return loginresponse;
    }

}
